package com.platform.mvc.login;

import com.application.api.entity.ResultEntity;
import com.application.common.utils.VerifyKit;
import com.application.service.UserService;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.platform.mvc.base.BaseValidator;
import com.platform.mvc.user.User;
import org.apache.commons.codec.digest.DigestUtils;

public class LoginValidator extends BaseValidator {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(LoginValidator.class);

	protected void validate(Controller c) {
		String actionKey = getActionKey();
		if (actionKey.endsWith("/login/vali") || actionKey.endsWith("/login")){
            String username = c.getPara("username");
            String password = c.getPara("password");
            String valicode = c.getPara("valicode");

            if(StrKit.notBlank(valicode)){
                if (!VerifyKit.verify(username, valicode)) {
                    addError("msg", "验证码错误");
                    return;
                }
            }

            User user = User.dao.findByUsername(username);
            if (user == null) {
                if(StrKit.notBlank(valicode)){//注册用户
                    user = new UserService().registerUser(username);
                    c.setAttr("user", user);
                    return;
                } else {
                    addError("msg", "用户名或密码错误");
                    return;
                }
            }

            if(StrKit.isBlank(valicode)){
                if (password == null || !user.getPassword().equals(DigestUtils.md5Hex(password))) {
                    addError("msg", "用户名或密码错误");
                    return;
                }
            }

            if("0".equals(user.get("status"))){
                addError("msg", "账号已停用，请联系管理员");
            }

            c.setAttr("user", user);
		} else if(actionKey.equalsIgnoreCase("/api/login/open")) {
            String openId = c.getPara("openid");
            String openType = c.getPara("open_type", "wx");

            String $sql = "select * from pt_user where openid = ? and open_type = ?";
            User user = User.dao.findFirst($sql, openId, openType);

            if(user != null && "0".equals(user.get("status"))){
                addError("msg", "账号已停用，请联系管理员");
            }

            c.setAttr("user", user);
        }
	}
	
	protected void handleError(Controller controller) {
		String actionKey = getActionKey();
        if (actionKey.endsWith("/login/vali") || actionKey.endsWith("/login")){
			controller.renderJson(new ResultEntity(400, controller.getAttr("msg")));
		}
	}
	
}
